use anyhow::Error;
use crate::{db::{Db, VectorCollection}, frame::Frame};

#[derive(Debug)]
pub struct CreateCollection {
    collection_name: String,
    dimension: usize,
}

impl CreateCollection {
    pub fn parse_from_frame(frame: Frame) -> Result<Self, Error> {
        let args = frame.get_args();
        if args.len() != 3 {
            return Err(Error::msg("ERR wrong number of arguments for 'CREATE_COLLECTION' command. Usage: CREATE_COLLECTION <name> <dimension>"));
        }
        
        let collection_name = args[1].to_string();
        let dimension = args[2].parse::<usize>().map_err(|_| Error::msg("ERR invalid dimension value"))?;

        if dimension == 0 {
            return Err(Error::msg("ERR dimension must be a positive integer"));
        }

        Ok(Self { collection_name, dimension })
    }

    pub fn apply(self, db: &mut Db) -> Result<Frame, Error> {
        
        if db.collections.contains_key(&self.collection_name) {
            return Err(Error::msg(format!("ERR collection '{}' already exists", self.collection_name)));
        }

        let collection = VectorCollection::new(self.dimension);
        db.create_collection(self.collection_name, collection);
        Ok(Frame::SimpleString("OK".into()))
    }
}